package com.platform.config;

import com.platform.comm.constants.GlobalConstant;
import com.platform.comm.web.mvc.handler.MultiRequestBodyArgumentResolver;
import com.platform.enums.formatters.CommFlagTypeFormatter;
import com.platform.enums.formatters.ConfValueModeFormatter;
import com.platform.enums.formatters.FunctionStatusFormatter;
import com.platform.enums.formatters.FunctionTypeFormatter;
import com.platform.kaptcha.handler.CaptchaHandler;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.format.FormatterRegistry;
import org.springframework.format.datetime.standard.DateTimeFormatterRegistrar;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.reactive.function.server.RequestPredicates;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * Description: 配置
 *
 * @author libin Created on 2019/7/17
 **/
@Configuration
@EnableAspectJAutoProxy
public class WebConfig implements WebMvcConfigurer {


    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addFormatter(new CommFlagTypeFormatter());
        registry.addFormatter(new ConfValueModeFormatter());
        registry.addFormatter(new FunctionTypeFormatter());
        registry.addFormatter(new FunctionStatusFormatter());
        DateTimeFormatterRegistrar registrar = new DateTimeFormatterRegistrar();
        registrar.setDateFormatter(DateTimeFormatter.ofPattern(GlobalConstant.DATE_1_PATTERN));
        registrar.setDateTimeFormatter(DateTimeFormatter.ofPattern(GlobalConstant.DATE_TIME_PATTERN));
        registrar.registerFormatters(registry);
    }

    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
        // 添加MultiRequestBody参数解析器
        argumentResolvers.add(new MultiRequestBodyArgumentResolver());
    }


    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplateBuilder().build();
    }


    @Bean
    public RouterFunction<ServerResponse> routeFunction(CaptchaHandler captchaHandler) {
        return RouterFunctions
                .route(RequestPredicates.POST("/auth/verifyCode")
                        .and(RequestPredicates.accept(MediaType.TEXT_PLAIN)), captchaHandler::handle);
    }
}
